package com.rainsoftware.LicenseSystem.controllers.api;

import com.rainsoftware.LicenseSystem.services.LicenseKeyService;
import com.rainsoftware.LicenseSystem.utils.StandardResponse;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@RestController
@RequestMapping("api/license-keys")
public class LicenseKeyController {

    @Autowired
    private LicenseKeyService licenseKeyService;

    @PostMapping("/generate")
    public ResponseEntity<String> generateLicenseKey(
                                                     @RequestParam String product_api_id,
                                                     @RequestParam Long duration,
                                                     @RequestParam Integer amount) {
        StandardResponse response = licenseKeyService.generateLicenseKey(product_api_id, duration, amount);
        return response.build();
    }

    @PostMapping("/delete")
    public ResponseEntity<String> deleteLicenseKeys(@RequestBody Map<String, Object> payload) {
        StandardResponse response = licenseKeyService.deleteLicenseKeys(payload);
        return response.build();
    }

    @GetMapping
    public ResponseEntity<String> queryLicenseKeys(@RequestParam(required = false) Integer product_id,
                                                   @RequestParam(required = false) String sort,
                                                   @RequestParam(required = false) Integer rows,
                                                   @RequestParam(required = false) Integer page,
                                                   @RequestParam(required = false) String search_for,
                                                   @RequestBody(required = false) String jsonBody
                                                    ) {
        if (jsonBody != null) {
            JSONObject json = new JSONObject(jsonBody);
            product_id = json.optInt("product_id",-1);
            sort = json.optString("sort");
            rows = json.optInt("rows");
            page = json.optInt("page");
            search_for = json.optString("search_for");
        }
        StandardResponse response = licenseKeyService.queryLicenseKeys(product_id, sort, rows, page, search_for);
        return response.build();
    }

    @PostMapping("/{id}")
    public ResponseEntity<String> onLicenseKeyQuery(@PathVariable int id, @RequestParam String action) {
        StandardResponse response = licenseKeyService.handleLicenseKeyAction(id, action);
        return response.build();
    }
}